import { observe } from "./observe/index"

export function initState(vm){
    const opts = vm.$options
//     数据劫持
    if(opts.data) {
        initData(vm)
    }
}
// 代理将this._data.xx => this.xx
function proxy(vm, target, key) {

    Object.defineProperty(vm, key, {
        get() {
            return vm[target][key];
        },
        set(newValue) {
            let value = vm[target][key];
            if (value === newValue) return;
            vm[target][key] = newValue;
        }
    });
}
function initData(vm) {
    let data = vm.$options.data;
    data = typeof data === 'function' ? data.call(vm):data;
    vm._data = data;

    // 观测数据
    observe(data)
    // 代理调用
    for(let key in data) {
        proxy(vm,'_data',key)
    }
}